package com.xuexi.demos.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Base64;

public class JwtUtils {

    private static final String SECRET = "BuffSiteSecretKeyForJWT@2023!"; // 32字符以上的密钥
    private static final long EXPIRATION = 24 * 60 * 60 * 1000; // 24小时

    // 生成JWT令牌
    public static String generateToken(String username) {
        try {
            return Jwts.builder()
                    .setSubject(username)
                    .setIssuedAt(new Date())
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                    .signWith(SignatureAlgorithm.HS512, SECRET)
                    .compact();
        } catch (Exception e) {
            // 如果JWT生成失败，返回一个简单的token
            return Base64.getEncoder().encodeToString((username + ":" + System.currentTimeMillis()).getBytes());
        }
    }

    // 验证并解析令牌
    public static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }
}